package stark.app.function.wifi;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.view.View;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.IntentUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.thanosfisherman.wifiutils.WifiUtils;
import com.thanosfisherman.wifiutils.wifiConnect.ConnectionErrorCode;
import com.thanosfisherman.wifiutils.wifiConnect.ConnectionSuccessListener;
import com.thanosfisherman.wifiutils.wifiState.WifiStateListener;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import stark.app.R;
import stark.app.databinding.FragmentWifiConnectDemoBinding;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.utils.WiFiUtil;

/**
 * Author：daizhongbin on 2022/4/28
 * Email：1027154338@qq.com
 * Desc:
 */
public class WifiConnectDemoFragment extends BaseNoModelFragment<FragmentWifiConnectDemoBinding> {

    private static final String[] PERMISSIONS = new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION

    };
    //是否被用户永久拒绝使用权限的标志
    private boolean isPerDeniedForever = false;
    private WifiAdapter mAdapter;

    @Override
    protected int onCreate() {
        return R.layout.fragment_wifi_connect_demo;
    }

    @Override
    protected void initView() {
        mDataBinding.btnReqPer.setOnClickListener(this);
        mDataBinding.btnEnableWifi.setOnClickListener(this);

        //rv
        mDataBinding.rvWifi.setLayoutManager(new LinearLayoutManager(getContext()));
        WifiAdapter adapter = new WifiAdapter();
        mAdapter = adapter;
        adapter.setOnItemClickListener(this);
        mDataBinding.rvWifi.setAdapter(adapter);
        adapter.setEmptyView(com.stark.irremote.lib.R.layout.layout_ir_no_data);
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onResume() {
        super.onResume();
        checkPermission();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        WifiStateObserver.stopListen();
    }

    @Override
    protected void onClickCallback(View v) {
        if (v == mDataBinding.btnReqPer) {
            handleClickReqPermission();
        } else if (v == mDataBinding.btnEnableWifi) {
            handleClickEnableWifi();
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        ScanResult scanResult = (ScanResult) adapter.getItem(position);
        if (WiFiUtil.isConnected(scanResult)) {
            ToastUtils.showShort("该热点已连接");
            return;
        }

        if (WiFiUtil.isOpened(scanResult)) {
            connectWifi(scanResult, "");
        } else {
            //显示密码弹框
            showPwdDialog(scanResult);
        }
    }

    private void checkPermission() {
        PermissionUtils.permission(PERMISSIONS)
                .callback(new PermissionUtils.SingleCallback() {
                    @Override
                    public void callback(boolean isAllGranted, @NonNull List<String> granted, @NonNull List<String> deniedForever, @NonNull List<String> denied) {
                        if (!isAllGranted) {
                            isPerDeniedForever = deniedForever != null && deniedForever.size() > 0;
                            showReqPermissionView();
                            return;
                        }
                        afterGetPermission();
                    }
                })
                .request();
    }

    private void showReqPermissionView() {
        mDataBinding.rvWifi.setVisibility(View.GONE);
        mDataBinding.llEnableWifi.setVisibility(View.GONE);
        mDataBinding.llReqPer.setVisibility(View.VISIBLE);
    }

    private void showEnableWifiView() {
        mDataBinding.rvWifi.setVisibility(View.GONE);
        mDataBinding.llEnableWifi.setVisibility(View.VISIBLE);
        mDataBinding.llReqPer.setVisibility(View.GONE);
    }

    private void showRvView() {
        mDataBinding.rvWifi.setVisibility(View.VISIBLE);
        mDataBinding.llEnableWifi.setVisibility(View.GONE);
        mDataBinding.llReqPer.setVisibility(View.GONE);
    }


    private WifiPwdDialog mPwdDialog;

    private void showPwdDialog(ScanResult scanResult) {
        if (mPwdDialog == null) {
            mPwdDialog = new WifiPwdDialog(getContext());
        }
        mPwdDialog.setListener(new WifiPwdDialog.IListener() {
            @Override
            public void onConnect(@NonNull String password) {
                connectWifi(scanResult, password);
            }
        });
        mPwdDialog.show();
    }

    private void afterGetPermission() {
        WifiStateObserver.startListen();
        WifiStateObserver.getWifiStateLiveData().observe(getViewLifecycleOwner(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean isWifiEnabled) {
                if (!isWifiEnabled) {
                    //显示wifi没有打开的提示控件
                    showEnableWifiView();
                    return;
                }
                showRvView();
                scanWifi();
            }
        });
    }

    private void handleClickReqPermission() {
        if (isPerDeniedForever) {
            //跳去设置中的位置权限界面
            Intent intent = IntentUtils.getLaunchAppDetailsSettingsIntent(AppUtils.getAppPackageName());
            startActivity(intent);
        } else {
            checkPermission();
        }
    }

    private void handleClickEnableWifi() {
        WifiUtils.withContext(getContext()).enableWifi(new WifiStateListener() {
            @Override
            public void isSuccess(boolean isSuccess) {
                if (!isSuccess) {
                    //没有成功打开，则需要跳转到设置界面，让用户手动打开，因为自Android10之后，通过代码无法自动打开wifi
                    Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");
                    startActivity(wifiSettingsIntent);
                }
            }
        });
    }

    @SuppressLint("MissingPermission")
    private void scanWifi() {
        /*WifiUtils.withContext(getContext())
                .scanWifi(new ScanResultsListener() {
                    @Override
                    public void onScanResults(@NonNull List<ScanResult> scanResults) {
                        if (mAdapter != null) {
                            mAdapter.setNewInstance(scanResults);
                        }
                    }
                })
                .start();*/
        NetworkUtils.WifiScanResults results = NetworkUtils.getWifiScanResult();
        if (mAdapter != null) {
            mAdapter.setNewInstance(results.getAllResults());
        }
    }

    private void connectWifi(@NonNull ScanResult scanResult, String pwd) {
        showDialog("连接中...");
        WifiUtils.withContext(getContext())
                .connectWith(scanResult.SSID, scanResult.BSSID, pwd)
                .setTimeout(40000)
                .onConnectionResult(new ConnectionSuccessListener() {
                    @Override
                    public void success() {
                        dismissDialog();
                        ToastUtils.showShort("连接成功");
                    }

                    @Override
                    public void failed(@NonNull ConnectionErrorCode errorCode) {
                        dismissDialog();
                        ToastUtils.showShort("连接失败");
                    }
                })
                .start();
    }
}
